import { plugin, Messagetype, segment } from 'alemon'
import request from 'request'
import fs from 'fs'

//图床的api，可以换自己的，随意，图床地址https://www.picgo.net（免费）
//图传生成的链接5分钟后失效，如果介意的话最好自己弄个key
//当图片没有失效时，不可重复上传同一张图片
let imageup =
  'chv_W62p_56237fd84ea0d8f73b07efcfc5bea8b24e7e35ba4b03d4257460d3fbedb8683e75a15990b61a24e9f1294b54e2a01a71f5cf32dc9986ec4e1c8b396c17aa55be' //图床api密钥
let bigjpg:string = '' //放大接口api密钥，前往https://bigjpg.com/zh获取（付费，免费的每月20张）

export class PluginName extends plugin {
  constructor() {
    super({
      dsc: '插件描述',
      rule: [
        {
          reg: /^(\/|#)?(图片|照片)放大/,
          fnc: 'fangda'
        },
        {
          reg: /^(\/|#)?放大查询/,
          fnc: 'chaxun'
        },
        {
          reg: /^(\/|#)?放大重试/,
          fnc: 'chongshi'
        }
      ]
    })
  }
  /**
   * https://bigjpg.com/
   * 流程：
   * 下载图片到本地
   * 将图片上传至图床，并获取链接
   * 带上链接请求bigjpg放大图片
   * 每隔10秒查询进度，直到出结果为止
   *
   * @param e oicq传递的事件参数e
   */

  async fangda(e: Messagetype): Promise<boolean> {
    if (bigjpg === '') {
      e.reply('请先填写第九行的key：“let bigjpg:string = \'\'”')
      return true
    }
    e.msg.content = e.msg.content.replace(/<(@!||.*)?[0-9a-zA-Z]+> ?/g, '')
    let help = e.msg.content.match(/帮助/)
    if (help && help[0] === '帮助') {
      e.reply(
        '/(图片|照片)放大(放大参数1~4) (降噪参数0~4)\n放大参数对应x2，x4，x8，x16\n降噪参数分别对应：无，低，中，高，最高\n例如：/图片放大1 4'
      )
      return true
    }
    let z = e.msg.content.match(/\d/g) //前放大倍数1-4，后降噪-1-3
    let st = 'art'
    if (e.msg.content.match(/(\/|#)?(图片|照片)放大.*/g)[1] === '照片') {
      st = 'photo'
    }
    console.log(`获取到的参数：${z}`)
    let x: number, y: number

    if (!z) {
      x = 1
      y = 3
    } else {
      console.log(z)
      let z0 = +z[0]
      let z1 = +z[1]
      if (z0 && z0 > 0 && z0 < 5) {
        x = z0
      } else if (z0 >= 5) {
        e.reply('放大倍数只能为1~4')
        return true
      }
      if (-1 < z1 && z1 < 5) {
        y = z1 - 1
      } else {
        e.reply('减噪值只能为0~4的整数')
        return true
      }
    }
    //下载图片
    const eventType = e.eventId.split(':')[0]
    if (eventType !== 'MESSAGE_CREATE' && eventType !== 'AT_MESSAGE_CREATE') {
      await e.reply('请在子频道发送')
      return false
    }

    if (!e.msg.attachments) {
      e.reply('请和图片一起发送')
      return false
    }
    let ffd: string, jz: string

    switch (x) {
      case 1:
        ffd = '×2'
        break
      case 2:
        ffd = '×4'
        break
      case 3:
        ffd = '×8'
        break
      case 4:
        ffd = '×16'
        break
    }
    switch (y) {
      case -1:
        jz = '无'
        break
      case 0:
        jz = '低'
        break
      case 1:
        jz = '中'
        break
      case 2:
        jz = '高'
        break
      case 3:
        jz = '最高'
        break
    }
    // console.log(`放大：${fd}\n降噪：${y}`);
    let file = `${process.cwd()}/data/fangda.jpg`
    request
      .get('https://' + e.msg.attachments[0].url)
      .on('error', (error: any) => {
        console.log(error)
      })
      .pipe(fs.createWriteStream(file))
      .on('finish', () => {
        console.log('下载完成')

        //上传到图床
        let formData = {
          key: imageup,
          source: fs.createReadStream(file)
        }

        request.post(
          { url: 'https://www.picgo.net/api/1/upload', formData: formData },
          function optionalCallback(err: any, formData: any, body: string) {
            if (err) {
              return console.error('upload failed:', err)
            }
            let obj = JSON.parse(body)
            if (obj.status_code !== 200) {
              e.reply('上传图片失败，五分钟后重试这张图')
              return true
            }
            //上传完成，请求放大接口
            //放大参数
            let data = {
              style: st,
              noise: y,
              x2: x,
              input: obj.image.image.url
            }

            let options = {
              url: 'https://bigjpg.com/api/task/',
              headers: {
                'X-API-KEY': bigjpg
              },
              form: {
                conf: JSON.stringify(data)
              }
            }

            request.post(options, (err: any, res: any, body: string) => {
              if (err) {
                console.log(err)
              } else {
                let fd = JSON.parse(body)
                console.log(fd)
                e.reply([
                  `放大:${ffd}；降噪:${jz}`,
                  `\n本月剩余次数：${fd.remaining_api_calls}`,
                  `\n本次任务id：${fd.tid}`,
                  `\n预计时长：${fd.minute}分钟内`
                ])

                //反复查询进度
                let id = setInterval(() => {
                  request(`https://bigjpg.com/api/task/${fd.tid}`, (err, res, body) => {
                    if (!err) {
                      let obj = JSON.parse(body)
                      if (body !== '{}') {
                        if (obj[fd.tid].status == 'success') {
                          console.log(body)
                          request
                            .get(obj[fd.tid].url)
                            .on('error', (error: any) => {
                              console.log(error)
                            })
                            .pipe(fs.createWriteStream(file))
                            .on('finish', () => {
                              console.log('下载完成')
                              e.sendImage(file, '成功力~')
                            })
                          clearInterval(id)
                        } else {
                          if (obj[fd.tid].status == 'error') {
                            console.log(obj)
                            e.reply(
                              `放大请求错误，请重新发送或发送“/放大重试${fd.tid}”`,
                              segment.reply(e.msg.id)
                            )
                            clearInterval(id)
                          }
                        }
                      }
                    }
                  })
                }, x * 15)
              }
            })
          }
        )
      })
  }
}
